package com.cwf.quality.common.strategy.filter;

import com.cwf.quality.common.enums.DataCheckFilterEnum;
import com.cwf.quality.model.dto.QualityResultInfo;
import com.cwf.quality.model.dto.datacheck.result.ValueEnumRangeCheckResult;
import com.cwf.quality.model.dto.datacheck.rule.CheckRuleInfo;
import com.cwf.quality.model.dto.datacheck.rule.DataCheckRuleInfo;
import com.cwf.quality.utils.SqlUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class ValueEnumRangeCheckFilter implements IDataCheckFilter {
    /**
     * 校验是否属于枚举范围
     *
     * @param dataCheckRuleInfo
     * @return
     */
    @Override
    public QualityResultInfo<ValueEnumRangeCheckResult> checkData(DataCheckRuleInfo dataCheckRuleInfo) {
        SqlUtils sqlUtils = dataCheckRuleInfo.getSqlUtils();

        Map<String, List<ValueEnumRangeCheckResult.ValueEnumRangeCount>> valueEnumRangeCountMap = new HashMap<>();

        List<CheckRuleInfo.ColumnEnumRange> columnEnumRangeList = dataCheckRuleInfo.getCheckRuleInfo().getColumnEnumRangeList();
        for (CheckRuleInfo.ColumnEnumRange columnEnumRange : columnEnumRangeList) {
            String columnName = columnEnumRange.getColumnName();
            String enumValues = StringUtils.join(columnEnumRange.getEnumValues(), ",");

            String sql = DataCheckFilterEnum.VALUE_ENUM_RANGE_CHECK.getSql()
                    .replace("{table}", dataCheckRuleInfo.getTableName())
                    .replace("{column}", columnName)
                    .replace("{enumValues}", enumValues);

            List<Map<String, Object>> mapList = sqlUtils.query4List(sql, -1);

            List<ValueEnumRangeCheckResult.ValueEnumRangeCount> valueEnumRangeCounts = new ArrayList<>();
            for (Map<String, Object> map : mapList) {
                Object columnValue = map.get(columnName);
                Long overEnumCount = (Long) map.get("over_enum_count");
                valueEnumRangeCounts.add(new ValueEnumRangeCheckResult.ValueEnumRangeCount(columnValue, overEnumCount));
            }
            valueEnumRangeCountMap.put(columnName, valueEnumRangeCounts);
        }
        QualityResultInfo qualityResultInfo = QualityResultInfo.builder()
                .code(0)
                .msg("成功")
                .result(new ValueEnumRangeCheckResult(valueEnumRangeCountMap))
                .build();
        return qualityResultInfo;
    }
}
